package cn.bai.mvc;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.util.List;

/**
 * Created by Admin on 12/23 0023.
 */
public class DaoImp<T> implements DAO<T> {
    public Class<T> clazz;
    public QueryRunner queryRunner = new QueryRunner();

    public DaoImp() {
        Type superClass = getClass().getGenericSuperclass();
        if (superClass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) superClass;
            Type[] types = parameterizedType.getActualTypeArguments();
            if (types != null && types.length > 0) {
                clazz = (Class<T>) types[0];
            }
        }
    }

    @Override
    public void update(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            queryRunner.update(connection, sql, args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection);
        }
    }

    @Override
    public T get(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection);
        }
        return null;
    }

    @Override
    public List<T> getList(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection);
        }
        return null;
    }

    @Override
    public <E> E getForValue(String sql, Object... args) {
        Connection connection = null;
        try {
            connection = JDBCUtil.getConnection();
            return (E) queryRunner.query(connection, sql, new ScalarHandler(), args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(connection);
        }
        return null;
    }
}
